<template>
 <div class="dashboard-container">
  <div class="welcome-text">您好，欢迎使用师生答题管理系统！</div>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>系统公告</span>
            <el-button v-if="isAdmin || isTeacher" type="primary" size="small" @click="openAnnouncementDialog">发布公告</el-button>
          </div>
          <div v-for="(item, index) in announcements" :key="index" class="announcement-item">
            <span>
              <div class="announcement-title">{{ item.title }}</div>
              <div class="announcement-content">{{ item.content }}</div>
              <div class="announcement-time">{{ item.createTime }}</div>
            </span>
          <span>
            <el-button v-if="isAdmin || isTeacher" type="danger" size="small" @click="deleteAnnouncement(item.id)">删除</el-button>
            <el-button v-if="isAdmin || isTeacher" type="primary" size="small" @click="editAnnouncement(item)">编辑</el-button>
          </span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>考试安排</span>
          </div>
          <div v-for="(item, index) in examSchedules" :key="index" class="exam-item">
            <div class="exam-info">
              <span>考试名称：{{ item.title }}</span>
              <span>考试时间：{{ item.examTime }}</span>
              <span>考试地点：{{ item.location }}</span>
              <span>监考老师：{{ item.teacher }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      </el-row>
    <!-- 公告编辑对话框 -->
    <el-dialog title="编辑公告" :visible.sync="announcementDialogVisible" width="30%">
      <el-form :model="announcementForm">
        <el-form-item label="标题">
          <el-input v-model="announcementForm.title"></el-input>
        </el-form-item>
        <el-form-item label="内容">
          <el-input type="textarea" v-model="announcementForm.content"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="announcementDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAnnouncement">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import request from '@/utils/request'

export default {
  name: 'Dashboard',
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  data() {
    return {
      announcements: [],
      examSchedules: [],
      announcementDialogVisible: false,
      announcementForm: {
        id: null,
        title: '',
        content: ''
      }
    }
  },
  computed: {
    isAdmin() {
      const userInfo = JSON.parse(localStorage.getItem('userInfo'))
      return userInfo && userInfo.studentId === 'admin' && userInfo.identity === '1'
    },
    isTeacher() {
      const userInfo = JSON.parse(localStorage.getItem('userInfo'))
      return userInfo && userInfo.identity == 1 && userInfo.studentId !== 'admin'
    }
  },
  created() {
    this.fetchDashboardData()
  },
 
  methods: {
    async fetchDashboardData() {
      try {
        const res = await request({
          url: '/api/dashboard/info',
          method: 'get'
        })
        if (res.code === '200') {
          console.log(res.data.announcements);
          console.log(res.data.examSchedules);
          console.log(res.data.announcements[0].id);
          this.announcements = res.data.announcements.map(item => ({
            id: item.id, // 确保 id 被正确设置
            title: item.title,
            content: item.content,
            createTime: item.createTime
          }))
          this.examSchedules = res.data.examSchedules
        }
      } catch (error) {
        console.error('获取数据失败:', error)
      }
    },
    openAnnouncementDialog() {
      this.announcementDialogVisible = true
      this.announcementForm = { id: null, title: '', content: '' }
    },
    editAnnouncement(item) {
      this.announcementDialogVisible = true
      this.announcementForm = { ...item }
    },
    async submitAnnouncement() {
      try {
        console.log(this.announcementForm,'1111');
        const userInfo = JSON.parse(localStorage.getItem('userInfo'))
        console.log(userInfo,'11111234');
        
        const url = this.announcementForm.id ? '/api/announcement/update' : '/api/announcement/create'
         // 创建公告时，不传递 id
        const data = this.announcementForm.id ? this.announcementForm : { 
          title: this.announcementForm.title,
          content: this.announcementForm.content
        }

        // 添加 userId 作为查询参数
        const params = this.announcementForm.id ? {} : { userId: userInfo.id }

        const res = await request({
          url,
          method: 'post',
          data,
          params
        })

        if (res.code === '200') {
          this.$message.success('公告提交成功')
          this.announcementDialogVisible = false
          this.fetchDashboardData()
        }
      } catch (error) {
        console.error('公告提交失败:', error)
      }
    },
    async deleteAnnouncement(id) {
      try {
        const res = await request({
          url: '/api/announcement/delete',
          method: 'post',
          data: { id }
        })
        if (res.code === '200') {
          this.$message.success('公告删除成功')
          this.fetchDashboardData()
        }
      } catch (error) {
        console.error('公告删除失败:', error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.clearfix{
  display:flex;
  justify-content: space-between;
}
.dashboard-container {
  padding: 20px;
}
.welcome-text {
  font-size: 20px;
  color: #409EFF;
  margin-bottom: 20px;
}
.box-card {
  margin-bottom: 20px;
}

.announcement-item {
  padding: 10px 0;
  border-bottom: 1px solid #eee;
  display:flex;
  justify-content: space-between;
  &:last-child {
    border-bottom: none;
  }
}

.announcement-title {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 5px;
}
.announcement-content {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.announcement-time {
  font-size: 12px;
  color: #999;
}

.exam-item {
  padding: 10px 0;
  border-bottom: 1px solid #eee;

  &:last-child {
    border-bottom: none;
  }
}

.exam-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
  font-size: 14px;
}
</style>